package com.voice.server.publish.device;

import com.alibaba.fastjson.JSONObject;
import com.voice.core.DefaultClient;
import com.voice.core.connection.entity.Stream;
import com.voice.core.connection.entity.StreamData;
import com.voice.core.utils.ResponseUtil;
import com.voice.server.connection.DeviceControllerConnection;
import com.voice.server.entity.Device;
import com.voice.server.entity.DevicePinYinCode;
import com.voice.server.enums.PushTypeEnum;
import com.voice.server.observer.impl.CmdObservable;
import com.voice.server.publish.PublishHandler;
import com.voice.server.repository.DevicePinYinCodeRepository;
import com.voice.server.repository.DeviceRepository;
import com.wangjiacai.utils.web.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


@Component("/device/pub/push/type")
@Transactional
public class PushTypeHandler implements PublishHandler<DeviceControllerConnection> {

    @Autowired
    private DeviceRepository deviceRepository;
    @Autowired
    private DefaultClient defaultClient;
    @Autowired
    private RedisService redisService;

    @Override
    public void handle(Stream stream,StreamData streamData, DeviceControllerConnection connection){
        JSONObject jsonObject=JSONObject.parseObject(new String(streamData.readAllData()));
        if(jsonObject==null) return;
        Integer type=jsonObject.getInteger("type");
        if(type!= PushTypeEnum.Device.getCode()) return;
        Device device=deviceRepository.findByDeviceKey(connection.getDeviceKey());
        device.setPushType(type);
        redisService.hashSet(CmdObservable.hashKey, device.getDeviceKey(), device.getPushType());
        deviceRepository.save(device);
        this.defaultClient.sendResponse(connection, stream.getStreamId(), ResponseUtil.success());
    }
}
